package com.cloudspace.jindun.activity.interphone;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;

import com.android.volley.error.VolleyError;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.adapter.MyChannelDetailAdapter;
import com.cloudspace.jindun.model.ChannelMemberListResult;
import com.cloudspace.jindun.model.CommonResult;
import com.cloudspace.jindun.model.Person;
import com.cloudspace.jindun.module.ActionItem;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.Convert;
import com.cloudspace.jindun.utils.MMAlert;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.window.MyPopupMenu;

import org.apache.http.HttpStatus;

import java.util.List;

/**
 * Created by zengxianhua on 17/2/11.
 */

public class MyChannelDetailActivity extends CustomTitleBaseActivity{
    private static final String TAG = MyChannelDetailActivity.class.getSimpleName();

    private MyPopupMenu menuPopup;
    private String mChannelId;

    private MyChannelDetailAdapter mMyChannelDetailAdapter;
    private SwipeMenuListView mMyChannelDetailListView;

    private View mAddChannelMemberView;
    private View.OnClickListener deleteClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            delChannel();
        }
    };
    private View.OnClickListener renameClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            InterphoneRemarkActivity.showActivity(MyChannelDetailActivity.this, mChannelId);
        }
    };

    public static void showActivity(Context context, String channelId){
        Intent intent = new Intent(context, MyChannelDetailActivity.class);

        intent.putExtra("channelid", channelId);

        if (!(context instanceof Activity)){
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_channel_detail, true);
        getTitleBar().setSimpleMode(getResources().getString(R.string.my_channel_detail),
                new ActionItem(R.drawable.linkmenu, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        menuPopup.showOrHideOverflow(getTitleBar().getRightView(),
                                getResources().getString(R.string.channeldetail_menu1),
                                getResources().getString(R.string.channeldetail_menu2),
                                deleteClick,
                                renameClick
                                );
                    }
                }));

        if (getIntent() != null){
            mChannelId = getIntent().getStringExtra("channelid");
        }

        initView();
    }

    private void initView() {
        mMyChannelDetailListView = (SwipeMenuListView) findViewById(R.id.duijiang_lv_channel_details_members);
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
                openItem.setBackground(new ColorDrawable(getResources().getColor(R.color.color_c8c7cd)));
                openItem.setWidth(Convert.dip2px(73));
                openItem.setTitle(getResources().getString(R.string.call_history_cancel));
                openItem.setTitleSize(16);
                openItem.setHeight(Convert.dip2px(57));
                openItem.setTitleColor(Color.WHITE);
                openItem.setMarginBottom(Convert.dip2px(3));
                menu.addMenuItem(openItem);

                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(getResources().getColor(R.color.color_ff3a31)));
                deleteItem.setWidth(Convert.dip2px(73));
                deleteItem.setTitleColor(Color.WHITE);
                deleteItem.setTitleSize(16);
                deleteItem.setHeight(Convert.dip2px(57));
                deleteItem.setTitle(getResources().getString(R.string.call_history_del));
                deleteItem.setMarginBottom(Convert.dip2px(3));
                menu.addMenuItem(deleteItem);
            }
        };

        mMyChannelDetailListView.setMenuCreator(creator);
        mMyChannelDetailListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        break;

                    case 1:
                        deleteAPerson(position);
                        break;

                    default:
                        break;
                }

                return false;
            }
        });
        mMyChannelDetailListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);

        mMyChannelDetailAdapter = new MyChannelDetailAdapter(this);
        mMyChannelDetailListView.setAdapter(mMyChannelDetailAdapter);

        mAddChannelMemberView = findViewById(R.id.addPersonLy);
        mAddChannelMemberView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Person> persons = mMyChannelDetailAdapter.getData();
                String memberIdStr = "";
                if (!ObjUtil.isEmpty(persons)){
                    memberIdStr = ",";

                    for (Person person : persons){
                        memberIdStr += person.getUserId() + ",";
                    }
                }

                ChannelAddMemberActivity.showActivity(MyChannelDetailActivity.this, mChannelId, memberIdStr);
            }
        });

        menuPopup = new MyPopupMenu(this);
    }

    //删除某个联系人
    private void deleteAPerson(int position) {
        List<Person> persons = mMyChannelDetailAdapter.getData();
        Person person = persons.get(position);

        if (person.getUserId() == UserSessionManager.getInstance().getUserId()){
            ToastMaker.showToastShort(R.string.cannot_delete_self);
            return;
        }

        if (person != null){
            API.getInstance().getChannelApi().delChannelMember(TAG, mChannelId,
                    person.getUserId(),
                    new ApiCallback<CommonResult>() {
                        @Override
                        public void handleResult(CommonResult result, VolleyError error) {
                            if (result != null && result.status == HttpStatus.SC_OK){
                                ToastMaker.showToastShort(getResources().getString(R.string.delete_success));
                                loadChannelData();
                            }
                        }
                    }.toastActionError()
            );
        }
    }

    private void delChannel() {
        API.getInstance().getChannelApi().deleteChannel(TAG, mChannelId, new ApiCallback<CommonResult>() {
            @Override
            public void handleResult(CommonResult result, VolleyError error) {
                if (result != null && result.status == 200){
                    showDeleteDialog(true);
                }else{
                    showDeleteDialog(false);
                }
            }
        });
    }

    private void showDeleteDialog(final boolean deleteSuccess) {
        MMAlert.showAlert(
                this,
                deleteSuccess ? getResources().getString(R.string.channel_delete_success) : getResources().getString(R.string.channel_delete_fail),
                getResources().getString(R.string.info),
                getResources().getString(R.string.iknow),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (deleteSuccess){
                            MyChannelDetailActivity.this.finish();
                        }
                    }
                }
        );
    }

    @Override
    protected void onStart() {
        super.onStart();

        loadChannelData();
    }

    private void loadChannelData() {
        API.getInstance().getChannelApi().getMyChannelMember(TAG, mChannelId, new ApiCallback<ChannelMemberListResult>() {
            @Override
            public void handleResult(ChannelMemberListResult result, VolleyError error) {
                if (result != null && result.status == 200 && error == null){
                    mMyChannelDetailAdapter.setDatas(result.data);
                }else if (error != null){
                    ToastMaker.showToastShort(error.getMessage());
                }
            }
        });
    }
}
